package com.google.code.jbauble.dao.mysql;

import java.lang.reflect.*;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.apache.log4j.Logger;

import com.google.code.jbauble.dao.SqlNative;
import com.google.code.jbauble.exception.DataAccessException;
import com.jolbox.bonecp.BoneCP;
import com.jolbox.bonecp.BoneCPConfig;
import com.mysql.jdbc.Driver;

public class MysqlNative implements SqlNative {
	protected List<BoneCP> pools = null;
	private int readMode = 0;
	
	public MysqlNative(String url, String db, String user, String pwd, int minPool, int maxPool, int readMode) {
		this(url, db, user, pwd, minPool, maxPool, 2, readMode);
	}
	
	public MysqlNative(String url, String db, String user, String pwd, int minPool, int maxPool, int partition, int readMode) {
		pools = createPools(url, db, user, pwd, minPool, maxPool, partition);
		sourceCount = pools.size();
		this.readMode = readMode;
	}
	
	private List<BoneCP> createPools(String url, String db, String user, String pwd, int minPool, int maxPool, int partition) {
		String[] ss = url.split(",");
		if (ss == null || ss.length < 1)
			return null;
		
		List<BoneCP> ds = new ArrayList();
		for (String s : ss) {
			ds.add(createPool(s, db, user, pwd, minPool, maxPool, partition));
		}
		
		return ds;
	}

	private BoneCP createPool(String url, String db, String user, String pwd, int minPool, int maxPool, int partition) {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		//设置连接池配置信息  
        BoneCPConfig config = new BoneCPConfig();
        //数据库的JDBC URL  
        config.setJdbcUrl("jdbc:mysql://"+url+"/"+db+"?useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true");
        //数据库用户名  
        config.setUsername(user);
        //数据库用户密码  
        config.setPassword(pwd);
        //数据库连接池的最小连接数  
        config.setMinConnectionsPerPartition(minPool);
        //数据库连接池的最大连接数  
        config.setMaxConnectionsPerPartition(maxPool);
        //  
        config.setPartitionCount(partition);
        //设置数据库连接池  
        try {
			return new BoneCP(config);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	protected Logger log = Logger.getLogger(MysqlNative.class);
	private int readIndex = 0;
	private int sourceCount = 0;
	
	/**
	 * 得到数据源，0读，1写
	 * @param type
	 * @return
	 * @throws SQLException 
	 */
	public Connection getConnection(int type) throws SQLException {
		if (type == 1)
				return pools.get(0).getConnection();
		
		if (sourceCount < 2)
			return pools.get(0).getConnection();
					
		if (readIndex >= (sourceCount - 1))
			readIndex = readMode == 0 ? 0 : 1;
		
		return pools.get(readIndex ++).getConnection();
	}
	
	public List queryForList(String sql, Object[] objs, final Class type) {
		Connection conn = null;
		try {
			conn = getConnection(0);
			QueryRunner runner = new QueryRunner();
			ResultSetHandler h = new BeanListHandler(type);
			return (List) runner.query(conn, sql, h, objs);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		finally {
			DbUtils.closeQuietly(conn);
		}
	}

	public Object queryForObject(String sql, Object[] objs, final Class type) {
		Connection conn = null;
		try {
			conn = getConnection(0);
			QueryRunner runner = new QueryRunner();
			ResultSetHandler h = new BeanHandler(type);
			return runner.query(conn, sql, h, objs);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		finally {
			DbUtils.closeQuietly(conn);
		}
	}
	
	public Long queryForLong(String sql, Object[] objs) {
		Connection conn = null;
		try {
			conn = getConnection(0);
			QueryRunner runner = new QueryRunner();
			return (Long)runner.query(conn, sql, new ScalarHandler(1), objs); 
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		finally {
			DbUtils.closeQuietly(conn);
		}
	}
	
	public int execute(String sql, Object[] objs) throws DataAccessException {
		Connection conn = null;
		try {
			conn = getConnection(1);
			QueryRunner runner = new QueryRunner();
			return runner.update(conn, sql, objs);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return 0;
		}
		finally {
			DbUtils.closeQuietly(conn);
		}
	}
	
	public long executeInsert(final String sql, final Object[] objs) throws DataAccessException {
		Connection conn = null;
		try {
			conn = getConnection(1);
			QueryRunner runner = new QueryRunner();
			runner.update(conn, sql, objs);
			return (Long)runner.query(conn, "SELECT LAST_INSERT_ID()", new ScalarHandler(1)); 
		} catch (SQLException e) {
			e.printStackTrace();
			return 0;
		}
		finally {
			DbUtils.closeQuietly(conn);
		}
	}
}
